package com.example.controller;

import com.example.entity.TShopOrder;
import com.example.entity.TShopProduct;
import com.example.service.ITShopOrderService;
import org.apache.catalina.LifecycleState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author y
 * @since 2025-10-14
 */
@RestController
public class TShopOrderController {

    @Autowired
    private ITShopOrderService orderService;

    @GetMapping("/save/{pid}/{uid}/{number}")
    public TShopOrder save(@PathVariable("pid") Long pid, @PathVariable("uid") Long uid, @PathVariable("number") Integer number){

        TShopOrder order = new TShopOrder();
        order.setPid(pid);


        List<String> hosts = new ArrayList<>();
        hosts.add("localhost");
        hosts.add("localhost");
        hosts.add("localhost");

        List<Integer> ports = new ArrayList<>();
        ports.add(8081);
        ports.add(8082);
        ports.add(8083);

        Random random = new Random();
        int rand = random.nextInt(hosts.size());


        //创建一个发送http请求的对象，就像浏览器一样
        RestTemplate restTemplate = new RestTemplate();
        /*
         * 参数1： 请求的地址
         * 参数2： 返回数据的类型
         * */
        TShopProduct product = restTemplate.getForObject("http://"+hosts.get(rand)+":"+ports.get(rand)+"/get/" + pid,
                TShopProduct.class);
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());





        order.setUid(uid);
        order.setNumber(number);
        orderService.save(order);
        return order;
    }

}
